<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptions">
      <template #form="{ form }">
        <VGroup>
          <el-select v-model="form.input.type" style="width: 130px">
            <el-option label="计划变更单号" value="change_no"></el-option>
            <el-option label="需求单号" value="demand_no"></el-option>
            <el-option label="采购单号" value="purchase_no"></el-option>
          </el-select>
          <VBatchInput v-model="form.input.value" placeholder="请输入" class="w-40" @search="query" />
        </VGroup>
        <VGroup>
          <el-select v-model="form.skuInfo.type" class="w-28">
            <el-option label="sku" value="sku"></el-option>
            <el-option label="赛盒SKU" value="sai_he_sku"></el-option>
            <el-option label="自定义sku" value="custom_sku"></el-option>
          </el-select>
          <VBatchInput v-model="form.skuInfo.value" placeholder="请输入" class="w-40" @search="query" />
        </VGroup>
        <VGroup>
          <el-select v-model="form.warehouse.type" class="w-28" @change="form.warehouse.value = []">
            <el-option label="目的仓平台" value="destination_warehouse"></el-option>
            <el-option label="目的仓" value="plan_destination_warehouse"></el-option>
          </el-select>
          <VSelect v-if="form.warehouse.type === 'destination_warehouse'" v-model="form.warehouse.value" placeholder="请选择" :options="options.destination_warehouse" multiple
            collapse-tags style="min-width: 160px" />
          <VSelect v-else v-model="form.warehouse.value" placeholder="请选择" :options="options.plan_destination_warehouse" multiple collapse-tags style="min-width: 160px" />
        </VGroup>
        <VSelect v-model="form.change_status" placeholder="审核状态" :options="options.change_status || []" multiple collapse-tags style="min-width: 160px" />
        <VCascader v-model="form.purchase_user_id" placeholder="采购人员" multiple collapse-tags style="min-width: 160px" />
        <VCascader v-model="form.create_user" placeholder="变更申请人" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.change_method" placeholder="变更类型" style="width: 120px" type="demandChange" />
        <VSelect v-model="form.change_reason" placeholder="变更原因" :options="options.change_reason" multiple collapse-tags style="min-width: 200px" />
        <VSelect v-model="form.is_new" placeholder="是否新品" :options="options.is_new" multiple collapse-tags filterable clearable style="min-width: 160px" />
        <VSelect v-model="form.is_special_purchase" placeholder="是否特采" :options="options.is_special_purchase" multiple collapse-tags filterable clearable
          style="min-width: 160px" />
        <VGroup>
          <el-select v-model="form.dateRange.type" style="width: 100px">
            <el-option label="申请日期" value="create_time"></el-option>
            <el-option label="审核日期" value="audit_time"></el-option>
          </el-select>
          <VDate v-model="form.dateRange.value" />
        </VGroup>
      </template>
      <template #toolbar_btns>
        <VAudit
          :auth="['/purchase/demand/change/program_manager_review', '/purchase/demand/change/purchase_confirmation', '/purchase/demand/change/purchasing_manager_audit', '/purchase/demand/change/financial_supervisor_audit']"
          field="pdc_id" url="/v1/purchase-demand/purchase-demand-change/batch-audit" type="primary" :confirms="[3]" :tableRef="tableRef" :list="options.batch_audit_status" @success="query" />
        <VButton auth="/purchase/demand/change/submit" :loading="loadings.submit" @click="handleBatch('submit')">批量提交
        </VButton>
        <VButton auth="/purchase/demand/change/void" :loading="loadings.cancel" @click="handleBatch('cancel')">批量作废
        </VButton>
        <VButton auth="/purchase/demand/change/back" :loading="loadings.back" @click="handleBatch('back')">批量反审
        </VButton>
        <VTotal :data="total"
          :options="[{ title: '待计划经理审核', key: 'plan_leader_num' },{ title: '待采购确认', key: 'purchase_confirm_num' }, { title: '待采购经理审核', key: 'purchase_leader_num' }, { title: '待采购处理', key: 'purchase_process_num' }]"
          class="ml-auto" />
        <VExport auth="/purchase/demand/change/derive" mainKey="pdc_id" :name="baseName" :tableRef="tableRef" task class="ml-auto" />
      </template>
    </VTable>
    <VLog ref="logRef" />
    <Change ref="changeRef" :options="options" log isChange @success="query" />
    <HandleDialog ref="handleDialogRef" :options="options" log @success="query" />
  </VPage>
</template>
  
<script setup lang="jsx">
import api from './api'
import HandleDialog from './components/HandleDialog'
import Change from '@/components/Change'
import { getOption } from '@/api/public'
import { ElMessage, ElMessageBox } from 'element-plus'
import { resMessage } from '@/utils/res'
import VTotal from '@/components/VTotal'
const route = useRoute()
const router = useRouter()

const baseName = 'purchase_demand_change'
const tableRef = ref()
const logRef = ref()
const loadings = reactive({})
// 查询
const query = () => {
  tableRef?.value.query()
}
// 获取options
const options = ref({})
Promise.all([
  getOption({ type: 'purchase_demand' }).then(res => res.data),
  getOption({ type: baseName }).then(res => res.data),
]).then(res => {
  options.value = res.reduce((acc, cur) => (((acc = { ...acc, ...cur }), acc)), {})
})

// 批量操作
const handleBatch = (name) => {
  const selection = tableRef.value.$table.getCheckboxRecords()
  if (!selection.length) {
    ElMessage.warning('请先选择行')
    return
  }
  const pdc_ids = selection.map(d => d.pdc_id)
  const showLoading = () => loadings[name] = true
  const closeLoading = () => loadings[name] = false
  const handle = {
    submit: () => {
      showLoading()
      api.submit({ pdc_ids }).then(res => {
        resMessage({
          res,
          success: () => {
            ElMessage.success('操作成功')
            query()
          }
        })
      }).finally(closeLoading)
    },
    back: () => {
      showLoading()
      api.back({ pdc_ids }).then(res => {
        resMessage({
          res,
          success: () => {
            ElMessage.success('操作成功')
            query()
          }
        })
      }).finally(closeLoading)
    },
    cancel: () => {
      ElMessageBox.confirm('是否确认作废订单？', '作废', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          showLoading()
          api.cancel({ pdc_ids }).then(res => {
            resMessage({
              res,
              success: () => {
                ElMessage.success('操作成功')
                query()
              }
            })
          }).finally(() => {
            closeLoading()
          })
        })
        .catch(() => {
          ElMessage({ type: 'info', message: '取消操作', })
        })
    },
  }
  handle[name]()
}

// 单行操作
const changeRef = ref()
const handleDialogRef = ref()
const handleRow = (name, row, rowIndex) => {
  const { demand_no, sku, pdc_id, sku_no, change_method, change_reason, change_remark, is_new, is_special_purchase } = row
  const changeData = row.change_after ? [Object.assign({ pdc_id, is_new, is_special_purchase }, row.change_after)] : null
  const data = row.change_before ? [Object.assign({ pdc_id, is_new, is_special_purchase }, row.change_before)] : null
  const showLoading = () => {
    loadings[name + rowIndex] = true
  }
  const closeLoading = () => {
    loadings[name + rowIndex] = false
  }
  const handle = {
    look: () => {
      changeRef?.value.open({ demand_no, sku, sku_no }, { look: true, data, changeData, change_method, change_reason, change_remark })
    },
    edit: () => {
      changeRef?.value.open({ demand_no, sku, sku_no }, { look: false, data, changeData, change_method, change_reason, change_remark })
    },
    back: () => {
      showLoading()
      api.back({ pdc_ids: [pdc_id] }).then(res => {
        resMessage({
          res,
          success: () => {
            ElMessage.success('操作成功')
            query()
          }
        })
      }).finally(closeLoading)
    },
    submit: () => {
      showLoading()
      api.submit({ pdc_ids: [pdc_id] }).then(res => {
        resMessage({
          res,
          success: () => {
            ElMessage.success('操作成功')
            query()
          }
        })
      }).finally(closeLoading)
    },
    cancel: () => {
      ElMessageBox.confirm('是否确认作废订单？', '作废', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          showLoading()
          api.cancel({ pdc_ids: [pdc_id] }).then(res => {
            resMessage({
              res,
              success: () => {
                ElMessage.success('操作成功')
                query()
              }
            })
          }).finally(() => {
            closeLoading()
          })
        })
        .catch(() => {
          ElMessage({ type: 'info', message: '取消操作', })
        })
    },
    handle: () => {
      handleDialogRef?.value.open(pdc_id)
    },
    log: () => {
      logRef?.value.open({ log_type: baseName, pdc_id })
    },
    toPath: () => {
      sessionStorage.setItem('_table_form', JSON.stringify({ tableForm: { input: { type: 'demand_no', value: row.demand_no } } }))
      router.push('/demand/demand')
    }
  }
  handle[name]()
}

// 列表配置
const tableOptions = reactive({
  rowConfig: { height: 92 },
  showHeaderOverflow: false,
  showOverflow: false,
  formConfig: {
    data: {
      skuInfo: { type: 'sku', value: '' },
      input: { type: 'change_no', value: '' },
      change_method: '',
      change_reason: [],
      warehouse: { type: 'destination_warehouse', value: [] }, // 组合
      dateRange: { type: 'create_time', value: [], range: true },
    }
  },
  columns: [
    { type: 'checkbox', width: 40, fixed: 'left' },
    {
      minWidth: 166, slots: {
        header: () => <div>计划变更单号</div>,
        default: ({ row }) => <Copy copy={row.change_no}><el-link type='primary' onClick={() => handleRow('look', row)}>{row.change_no}</el-link></Copy>
      }
    },
    {
      minWidth: 150, slots: {
        header: () => <div>计划单号<br />计划类型</div>,
        default: ({ row }) => <div>
          <el-link type='primary' onClick={() => handleRow('toPath', row)}>{row.demand_no}</el-link>
          <div>{row.demand_type_name}</div>
        </div>
      }
    },
    {
      minWidth: 160, slots: {
        header: () => <div>变更申请人<br />变更申请时间</div>,
        default: ({ row }) => <div>
          <VText value={row.create_user} />
          <VText value={row.create_time} />
        </div>
      }
    },
    {title: '变更SKU', field: 'sku', minWidth: 100, slots: {
      default: ({row}) => <div>
          {row.is_new === 2 ? <el-tag type="success" effect="dark" class='mr-1 mb-1'>新</el-tag> : ''}
          {row.is_special_purchase === 2 ? <el-tag type="danger" effect="dark">特</el-tag> : ''}
          <VText value={row.sku} />
        </div>
    }},
    {
      minWidth: 300, slots: {
        header: () => <div>变更信息</div>,
        default: ({ row, rowIndex }) => {
          const { change_type, change_info, change_num } = row
          return <div>
            <VText title="需求ID" value={row.sku_no} />
            <VText value={change_info} />
            {change_type === 1 ? <el-button link type='primary' onClick={() => handleRow('look', row, rowIndex)}>详细信息<i class="dk-iconfont icon-DArrowRight" /></el-button> : <VText title='数量' value={change_num} />}
          </div>
        }
      }
    },
    {
      minWidth: 100, slots: {
        header: () => <div>变更类型</div>,
        default: ({ row }) => <VText value={row.change_method_name} />
      }
    },
    {
      minWidth: 100, slots: {
        header: () => <div>变更原因</div>,
        default: ({ row }) => <VText value={row.change_reason_name} line={3} />
      }
    },
    {
      minWidth: 140, slots: {
        header: () => <div>变更备注</div>,
        default: ({ row }) => <VText value={row.change_remark} line={3} />
      }
    },
    {
      minWidth: 190, slots: {
        header: () => <div>变更前采购信息</div>,
        default: ({ row, rowIndex }) => {
          const purchase = row.purchase || []
          if (!purchase.length) return <strong>未采购</strong>
          const content = () => purchase.map(d => <div>
            <VText title='采购单' value={d.purchase_no} />
            <VText title='采购数量' value={d.purchase_num} />
            <VText title='采购单状态' value={d.audit_status_name} />
          </div>)
          return <VMore value={content} key={rowIndex} />
        }
      }
    },
    {
      minWidth: 140, slots: {
        header: () => <div>审核状态</div>,
        default: ({ row }) => {
          return <VText value={row.change_status_name} line={3} />
        }
      }
    },
    {
      minWidth: 170, slots: {
        header: () => <div>审核人<br />审核时间</div>,
        default: ({ row }) => <div>
          <VText value={row.audit_user} />
          <VText value={row.audit_time} />
        </div>
      }
    },
    {
      minWidth: 120, slots: {
        header: () => <div>审核备注</div>,
        default: ({ row }) => <VText value={row.audit_remark} line={3} />
      }
    },
    {
      minWidth: 180, slots: {
        header: () => <div>采购处理信息</div>,
        default: ({ row }) => <div>
          <VText title='采购人员' value={row.purchase_user_name} />
          <VText value={row.purchase_process_status_name} />
        </div>
      }
    },
    {
      minWidth: 100, slots: {
        header: () => <div>采购是否<br />接受变更</div>,
        default: ({ row }) => <VText value={row.is_purchase_receive_name} />
      }
    },
    {
      minWidth: 120, slots: {
        header: () => <div>采购备注</div>,
        default: ({ row }) => <VText value={row.purchase_remark} line={3} />
      }
    },
    {
      title: '操作', width: 120, fixed: 'right', slots: {
        default: ({ row, rowIndex }) => {
          const { change_status } = row
          // change_status	变更状态: 1待提交 2待计划经理审核 3待采购确认 4待采购经理审核 5待财务主管审核 6待采购处理 7已处理 8已驳回 9已作废 10采购不接受变更
          return <div class='nm flex flex-wrap gap-x-2 gap-y-1'>
            {row.change_type !== 2 ? <VButton auth="/purchase/demand/change/view" link type="primary" onClick={() => handleRow('look', row)}>查看</VButton> : ''}
            {[1, 8, 10].includes(change_status) ? <VButton auth="/purchase/demand/change/edit" link type="primary" onClick={() => handleRow('edit', row, rowIndex)}>编辑</VButton> : ''}
            {[1, 8, 10].includes(change_status) ? <VButton auth="/purchase/demand/change/submit" link type="primary" loading={loadings['submit' + rowIndex]} onClick={() => handleRow('submit', row, rowIndex)}>提交</VButton> : ''}
            {[6].includes(change_status) ? <VButton auth="/purchase/demand/change/procurement_processing" link type="primary" loading={loadings['handle' + rowIndex]} onClick={() => handleRow('handle', row, rowIndex)}>采购处理</VButton> : ''}
            {[2,3,4,5,6].includes(change_status) ? <VButton auth="/purchase/demand/change/back" link type="primary" loading={loadings['back' + rowIndex]} onClick={() => handleRow('back', row, rowIndex)}>反审</VButton> : ''}
            {[1, 8, 10].includes(change_status) ? <VButton auth="/purchase/demand/change/void" link type="primary" loading={loadings['cancel' + rowIndex]} onClick={() => handleRow('cancel', row, rowIndex)}>作废</VButton> : ''}
            <VButton auth="/purchase/demand/change/logs" link type="primary" onClick={() => handleRow('log', row, rowIndex)}>日志</VButton>
          </div>
        }
        //         状态对应的操作：
        // 待提交（查看、编辑、提交、作废、日志）
        // 待计划经理审核（查看、计划经理审核、日志）
        // 待采购确认（查看、采购确认、日志）
        // 待采购经理审核（查看、采购经理审核、日志）
        // 待财务主管审核（查看、财务主管审核、日志）
        // 待采购处理（查看、采购处理）
        // 已处理（查看、日志）
        // 已驳回（查看、编辑、提交、作废、日志）
        // 已作废（查看、日志）
        // 采购不接受变更（查看、编辑、提交、作废、日志）
      }
    },
  ],
  proxyConfig: {
    autoLoad: false,
    ajax: {
      query: ({ page, form }) => {
        api.total({ ...page, ...form }).then(res => {
          total.value = res.data
        })
        return api.query({ ...form, ...page })
      }
    }
  }
})
// 统计数据
const total = ref({})
</script>
  